<?php
/*
* $Author ：PHPYUN开发团队
*
* 官网: http://www.phpyun.com
*
* 版权所有 2009-2019 宿迁鑫潮信息技术有限公司，并保留所有权利。
*
* 软件声明：未经授权前提下，不得用于商业运营、二次开发以及任何形式的再次发布。
 */
class chat_model extends model{
    /**
     * 查询单个直聊用户
	 * $whereData 	 查询条件
     * $data 		 自定义处理数组
     */
    public function getMember($whereData, $data = array()) {
        
        $field  =  empty($data['field']) ? '*' : $data['field'];
        
        $member  	=  $this -> select_once('chat_member', $whereData, $field);  
		
        if (!empty($member['avatar'])){
            
            $member['avatar']  = checkpic($member['avatar'] , $this->config['sy_chat_logo']);
        }
        
        return $member;    
	}
	/**
	 * 查询多个直聊用户
	 * $whereData 	 查询条件
	 * $data 		 自定义处理数组
	 */
	public function getMemberList($whereData, $data = array()) {
	    
	    $field  =  empty($data['field']) ? '*' : $data['field'];
	    
	    $List   =  $this -> select_all('chat_member', $whereData, $field);
	    
	    return $List;
	}
	/**
	 * 添加直聊用户
	 * $upData      要修改的数据
	 * $whereData 	 查询条件
	 */
	public function addMember($data) 
	{
	    if (!empty($data)){
	        
	        $nid  =  $this -> insert_into('chat_member',$data);
	    }
	    
	    return $nid;
	}
	/**
	 * 修改直聊用户
	 * $upData      要修改的数据
	 * $whereData 	 查询条件
	 */
	public function upMember($upData,$whereData) {
	    
	    if (!empty($whereData)){
	        
	        $nid  =  $this -> update_once('chat_member',$upData,$whereData);
	    }
	    
	    return $nid;
	}
	/**
	 * 保存消息
	 * @param 引用字段：$data:字段
	 */
	public  function addChatLog($data=array()){
	    
	    $nid    =   $this -> insert_into('chat_log', $data);
	    
	    return $nid;
	}
    /**
     * 查询聊天记录
	 * $whereData 	 查询条件
     * $data 		 自定义处理数组
     */
	public function getChatLog($whereData, $data = array('utype'=>null)) {
        
        $field  =  empty($data['field']) ? '*' : $data['field'];
        
        $List  	=  $this -> select_once('chat_log', $whereData, $field);  
        
        if ($data['utype']){
            
            $List['sendTime']  =  ceil($List['sendTime']/1000);
            $List['sendTime_n']=  date('Y-m-d H:i',$List['sendTime']);
        }
        return $List;    
	}
	/**
	 * 查询聊天记录
	 * $whereData 	 查询条件
	 * $data 		 自定义处理数组
	 */
	public function getChatLogList($whereData, $data = array()) {
	    
	    $field  =  empty($data['field']) ? '*' : $data['field'];
	    
	    $List   =  $this -> select_all('chat_log', $whereData, $field);
	    
	    return $List;
	}
	/**
	 * 修改消息
	 * $upData      要修改的数据
	 * $whereData 	 查询条件
	 */
	public function upChatLog($upData,$whereData) {
	    
	    if (!empty($whereData)){
	        
	        $nid  =  $this -> update_once('chat_log',$upData,$whereData);
	    }
	    
	    return $nid;
	}
	/**
	 * 查询聊天数量
	 * $whereData 	 查询条件
	 */
	public function getChatLogNum($whereData) {
	    
	    $num  =  $this -> select_num('chat_log', $whereData);
	    
	    return $num;
	}
	/**
	 * 删除聊天记录，按条件分为删除全部记录和单个人记录
	 * $whereData 	 查询条件
	 */
	public function delChatLog($data = array()) {
	    
	    if(!empty($data['toid'])){
	        
	        $br  =  $this->getBeginid($data);
	        
	        if (!empty($br['beginid'])){
	            
	            $this -> delete_all('chat_log', array('beginid'=>$br['beginid']), '');
	        }
	    }elseif(!empty($data['where'])){
	        
	        $where	=  $data['where'];
	        
	        if (!empty($where['id'])){
	            
	            $chats  =  $this->select_all('chat_log',$where,'`beginid`');
	            
	            if (!empty($chats)){
	                
	                foreach ($chats as $v){
	                    
	                    $b[]  =  $v['beginid'];
	                }
	                $beginid  =  array_unique($b);
	            }
	        }
	        
	        $nid	=  $this -> delete_all('chat_log', $where, '');
	        
	        if (!empty($where['id'])){
	            
	            // 批量删除时更新最新一条记录
	            $nowChats  =  $this->select_all('chat_log',array('beginid'=>array('in_s',implode("','", $beginid)),'groupby'=>'beginid'),'MAX(id) as maxid');
	            
	            if (!empty($nowChats)){
	                
	                foreach ($nowChats as $v){
	                    
	                    $lid[]  =  $v['maxid'];
	                }
	                
	                $this-> update_once('chat_log',array('last'=>1),array('id'=>array('in',pylode(',', $lid))));
	            }
	        }
	        
	        return $nid;
	    }
	}
	/**
	 * 查询聊天记录
	 */
    public function getHistory($uid, $usertype){
        
        $time      =  strtotime('-30 day') * 1000;
        
        $history   =  array();
        
        $chatfrom  =  $this -> getChatLogList(array('from'=>$uid,'fusertype'=>$usertype,'last'=>1,'sendTime'=>array('>',$time),'orderby'=>'id','limit'=>300),array('field'=>'`id`,`beginid`,`from`,`to`,`fusertype`,`tusertype`,`sendTime`,`content`'));
       
        $chatto    =  $this -> getChatLogList(array('to'=>$uid,'tusertype'=>$usertype,'last'=>1,'sendTime'=>array('>',$time),'orderby'=>'id','limit'=>300),array('field'=>'`id`,`beginid`,`from`,`to`,`fusertype`,`tusertype`,`sendTime`,`content`'));
       
        if ($chatfrom || $chatto){
            
            $chats    =  array_merge($chatfrom,$chatto);
            //将chats中重新按id排序
            $sort  =  array(
                'direction'  =>  'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
                'field'      =>  'id',       //排序字段
            );
            $arrSort  =  array();
            foreach($chats as $uniqid => $row){
               
                foreach($row as $key=>$value){
                   
                    $arrSort[$key][$uniqid]  =  $value;
                }
            }
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $chats);
           
            foreach ($chats as $v){
               
                if ($v['from'] == $uid){
                   
                    $fuid[]  =  $v['to'];
                   
                }elseif ($v['to']==$uid){
                   
                    $fuid[]  =  $v['from'];
                }
            }
            $fuid    =  array_unique($fuid);
            
            $from    =  $this -> select_all('chat_member', array('uid'=>array('in',pylode(',', $fuid))));
            $unread  =  $this -> select_all('chat_log',array('to'=>$uid,'tusertype'=>$usertype,'status'=>2,'sendTime'=>array('>',$time),'orderby'=>'id','groupby'=>'`from`'),'`from`,`fusertype`,count(*) as `num`');
             
            if ($usertype == 2 || $usertype == 3){
                
                $resume  =  $this -> select_all('resume', array('uid'=>array('in',pylode(',', $fuid))),'`uid`,`name`,`sex`,`nametype`,`def_job`');
                $down    =  $this -> select_all('down_resume', array('comid'=>$uid,'uid'=>array('in',pylode(',', $fuid))),'`uid`');
                $sq      =  $this -> select_all('userid_job', array('com_id'=>$uid,'uid'=>array('in',pylode(',', $fuid))),'`uid`');
                
                foreach ($resume as $k=>$v){
                    
                    $nameArr  =  array();
                    $nameArr['name']      =  $v['name'];
                    $nameArr['sex']       =  $v['sex'];
                    $nameArr['nametype']  =  $v['nametype'];
                    $nameArr['eid']       =  $v['def_job'];
                    
                    $resume[$k]['linkman']  =  $this->setUsernameShow($nameArr);
                    foreach ($down as $dv){
                        if ($v['uid'] == $dv['uid']){
                            $resume[$k]['linkman']  =  $v['name'];
                        }
                    }
                }
            }
            if ($usertype == 1){
                
                $usersq    =  $this -> select_all('userid_job', array('uid'=>$uid,'com_id'=>array('in',pylode(',', $fuid))),'`com_id`');
            }
            foreach ($from as $k=>$v){
                $from[$k]['unread']  =  0;
                $from[$k]['down']    =  0;
                $from[$k]['sq']      =  0;
                foreach ($unread as $uval){
                    if ($v['uid'] == $uval['from'] && $v['usertype'] == $uval['fusertype']){
                        $from[$k]['unread']  =  $uval['num'];
                    }
                }
                if (!empty($down)){
                    foreach ($down as $dval){
                        if ($v['uid'] == $dval['uid']){
                            $from[$k]['down']  =  1;
                        }
                    }
                }
                if (!empty($sq)){
                    foreach ($sq as $sval){
                        if ($v['uid'] == $sval['uid']){
                            $from[$k]['sq']  =  1;
                        }
                    }
                }
                if (!empty($usersq)){
                    foreach ($usersq as $uval){
                        if ($v['uid'] == $uval['com_id']){
                            $from[$k]['sq']  =  1;
                        }
                    }
                }
                if (!empty($resume)){
                    foreach ($resume as $rval){
                        if ($v['uid'] == $rval['uid']){
                            $from[$k]['linkman']  =  $rval['linkman'];
                        }
                    }
                }
            }
            foreach ($chats as $key=>$val){
                foreach ($from as $k=>$v){
                    if (($val['from']==$v['uid'] && $val['fusertype'] == $v['usertype']) || ($val['to']==$v['uid'] && $val['tusertype'] == $v['usertype'])){
                        
                        if ($val['from'] == $uid){
                            $hkey  =  $val['to'];
                        } elseif ($val['to'] == $uid){
                            $hkey  =  $val['from'];
                        }
                        
                        if (isset($hkey)){
                            $msg        =  array();
                            $msg['id']  =  $hkey;
                            if (strpos($val['content'],'img[http')!==false){
                                $msg['content']  =  '[图片]';
                            }elseif (strpos($val['content'],'inviteid=')!==false){
                                $msg['content']  =  '面试消息';
                            }elseif (strpos($val['content'],'eid=')!==false){
                                $msg['content']  =  '简历消息';
                            }elseif (strpos($val['content'],'jobid=')!==false){
                                $msg['content']  =  '职位消息';
                            }else{
                                $msg['content']  =  $val['content'];
                            }
                            $msg['time']  =  date('Y-m-d',ceil($val['sendTime']/1000));
                            $msg['down']  =  $v['down'];
                            $msg['sq']    =  $v['sq'];
                            if(!empty($v['unread'])){
                                $msg['unread']  =  $v['unread'];
                            }
                            if ($val['from'] == $uid){
                                $msg['mine']    =  true;
                                $msg['tusertype']  =  $val['tusertype'];
                                $msg['fusertype']  =  $val['fusertype'];
                            }elseif ($val['to'] == $uid){
                                $msg['mine']    =  false;
                                $msg['tusertype']  =  $val['fusertype'];
                                $msg['fusertype']  =  $val['tusertype'];
                            }
                            $msg['username']    =  $v['nickname'];
                            $msg['usertype']    =  $v['usertype'];
                            $msg['linkman']     =  $v['linkman'];
                            $msg['avatar']      =  checkpic($v['avatar'] , $this->config['sy_chat_logo']);
                            
                            $history[]  =  $msg;  
                        }
                    }
                }
            }
        }
        return $history;
   }
   /**
    * 更新并获取用户信息
    * @param string $uid
    * @return string
    */
   function userinfo($data = array('uid'=>'','usertype'=>'','history'=>''))
   {
       $bArr  =  array(
           'uid'       =>  $data['uid'],
           'usertype'  =>  $data['usertype']
       );
       if (!empty($data['nowid']) && !empty($data['nowtype'])){
           
           $bArr['nowid']    =  $data['nowid'];
           $bArr['nowtype']  =  $data['nowtype'];
       }
       
       $user  =  $this -> getBeginInfo($bArr);
       
       $this -> checkMember($user);
       
       //聊天用户信息
       $return['mine'] = array(
           'avatar'    =>  checkpic($user['avatar']),
           'id'        =>  $user['uid'],
           'username'  =>  $user['nickname'],
           'usertype'  =>  $user['usertype'],
           'linkman'   =>  $user['linkman'],
           'identity'  =>  $user['identity']
       );
       if (!empty($data['history'])){
           
           $return['history']  =  $this -> getHistory($user['uid'], $user['usertype']);
       }
       return $return;
   }
   /**
    * 判断聊天用户
    * @param 表：chat_member
    * @param 引用字段：$data:字段
    */
   public function checkMember($chat = array())
   {
       $chatMember  =  $this -> getMember(array('uid'=>$chat['uid'],'usertype'=>$chat['usertype']),array('field'=>'`uid`,`nickname`,`avatar`,`linkman`'));
       
       $arr  =  array(
           'nickname'  =>  $chat['nickname'],
           'avatar'    =>  $chat['avatar'],
           'linkman'   =>  $chat['linkman']
       );
       if (!empty($chatMember)){
           
           if ($chatMember['nickname'] != $arr['nickname'] || $chatMember['avatar'] != $arr['avatar'] || $chatMember['linkman'] != $arr['linkman']){
               $this -> upMember($arr,array('uid'=>$chat['uid'],'usertype'=>$chat['usertype']));
           }
           
       }else{
           
           $arr['uid']       =  $chat['uid'];
           $arr['usertype']  =  $chat['usertype'];
           
           $this -> addMember($arr);
           
           include_once ('log.model.php');
           
           $LogM = new log_model($this->db, $this->def);
           
           $LogM -> addMemberLog($chat['uid'],$chat['usertype'],'用户：'.$chat['uid'].',聊天注册成功');
           
       }
   }
   function getBeginInfo($data = array())
   {
       include_once('userinfo.model.php');
       
       $userinfoM  =  new userinfo_model($this->db, $this->def);
       
       if ($data['usertype'] == 1){
           
           $field  =  '`name`,`photo`,`phototype`,`photo_status`,`sex`,`nametype`,`def_job`';
           
       }elseif ($data['usertype']==2){
           
           $field  =  '`name`,`shortname`,`logo`,`logo_status`,`linkman`';
           
       }elseif ($data['usertype']==3){
           
           $field  =  '`realname`,`com_name`,`photo_big`,`photo_status`';
       }
       $userinfo   =  $userinfoM -> getUserInfo(array('uid'=>$data['uid']),array('usertype'=>$data['usertype'],'field'=>$field));
       
       if ($data['usertype'] == 1){
           
           $user['nickname']  =  $userinfo['name'];
           
           $photoArr  =  array('photo' => $userinfo['photo'], 'phototype' => $userinfo['phototype'], 'photo_status' => $userinfo['photo_status'], 'sex' => $userinfo['sex']);
           
           $user['avatar']    =  $this->setResumePhotoShow($photoArr);
           
           if (!empty($data['nowtype']) && $data['nowtype'] != 1){
               
               $down  =  $this->select_num('down_resume',array('uid'=>$data['uid'],'comid'=>$data['nowid']));
               
               if ($down > 0){
                   
                   $user['linkman']   =  $userinfo['name'];
               }else{
                   
                   $nameArr  =  array(
                       'name'     => $userinfo['name'],
                       'sex'      => $userinfo['sex'],
                       'nametype' => $userinfo['nametype'],
                       'eid'      => $userinfo['def_job']
                   );
                   $user['linkman']   =  $this->setUsernameShow($nameArr);
               }
               
               $user['nowtype']   =  $data['nowtype'];
               $user['name']      =  $userinfo['name'];
               
           }else{
               
               $user['linkman']   =  $userinfo['name'];
           }
           
           $expect  =  $this->select_once('resume_expect',array('uid'=>$data['uid'],'defaults'=>1),'`name`');
           
           if (!empty($expect)){
               
               $user['identity']  =  $expect['name'];
               
           }else{
               
               $user['identity']  =  '求职者';
           }
           
       }elseif ($data['usertype'] == 2){
           
           $name  =  $userinfo['name'];
           
           $user['nickname']  =  !empty($userinfo['shortname']) ? $userinfo['shortname'] : $name;
           
           if (!empty($userinfo['logo']) && $userinfo['logo_status'] == 0){
               
               $user['avatar']  =  $userinfo['logo'];
           }else{
               $user['avatar']  =  $this->config['sy_unit_icon'];
           }
           
           $user['linkman']   =  $userinfo['linkman'];
           
           $user['identity']  =  $user['nickname'].'.招聘者';
           
       }elseif ($data['usertype'] == 3){
           
           $user['nickname']  =  $userinfo['realname'];
           
           if (!empty($userinfo['photo_big']) && $userinfo['photo_status'] != 0){
               
               $user['avatar']  =  $userinfo['photo_big'];
           }else{
               $user['avatar']  =  $this->config['sy_lt_icon'];
           }
           
           $user['linkman']   =  $user['nickname'];
           
           $user['identity']  =  $userinfo['com_name'].'.招聘者';
           
       }
       $user['uid']       =  $data['uid'];
       $user['usertype']  =  $data['usertype'];
       
       return $user;
   }
   function beginChat($data = array())
   {
       // 首先处理接受方信息
       $this -> userinfo(array('uid'=>$data['fromid'],'usertype'=>$data['fusertype']));
       //二人聊天专用id，这两个人的聊天记录，就按这个查询
       $br  =  $this->getBeginid($data);
       
       $beginid  =  $br['beginid'];
       
       $chated   =  $this -> getChatLog(array('beginid'=>$beginid,'sendTime'=>array('>',strtotime('-30 day') * 1000)),array('field'=>'`id`'));
       
       // 两人没有聊天记录，或者30天没有聊天记录，才需要重新发送
       if ($br['ischat'] == false || empty($chated)){
           
           $job_href  =  '';
           //个人、企业、猎头发的消息不同
           if ($data['tusertype'] == 1){
               
               $job_href  =  '';
           }else{
               $job_href  =  '感谢查看我的简历！';
           }
           
           $content  =  '你好！'.$job_href;
           
           $from  =  $this -> getBeginInfo(array('uid'=>$data['fromid'],'usertype'=>$data['fusertype']));
           $to    =  $this -> getBeginInfo(array('uid'=>$data['toid'],'usertype'=>$data['tusertype']));
           
           $this -> sendChat($from,$to,$content,$data['timestamp'],$beginid);
       }
   }
   /**
    * 发送聊天
    */
   function sendChat($from,$to,$content,$sendtime,$beginid)
   {
       $this -> upChatLog(array('last'=>0), array('beginid'=>$beginid));
       
       $data['beginid']   =  $beginid;
       $data['from']      =  $from['uid'];
       $data['to']        =  $to['uid'];
       $data['fname']     =  $from['nickname'];
       $data['tname']     =  $to['nickname'];
       $data['fusertype'] =  $from['usertype'];
       $data['tusertype'] =  $to['usertype'];
       $data['content']   =  $content;
       $data['sendTime']  =  $this->checkTime($sendtime);
       $data['type']      =  'friend';
       $data['status']    =  1;
       $data['last']      =  1;
       $data['msgtype']   =  'char';
       
       $success = $this -> addChatLog($data);
   }
   /**
    * 查询两人聊天专用id
    * @param array $data
    */
   function getBeginid($data = array())
   {
       // 查询、处理聊天关系
       $farr  =  array(
           'uid'        =>  $data['fromid'],
           'usertype'   =>  $data['fusertype'],
           'fid'        =>  $data['toid'],
           'fusertype'  =>  $data['tusertype']
       );
       $friend  =  $this->getFriend($farr);
       if (empty($friend)){
           //二人聊天专用id，这两个人的聊天记录，就按这个查询
           $beginid  =  $this->searchBeginid(array('toid'=>$data['toid'],'fromid'=>$data['fromid'],'tusertype'=>$data['tusertype'],'fusertype'=>$data['fusertype']));
           
           $farr['beginid']  =  $beginid;
           
           $this->addFriend($farr);
           
           $ischat  =  false;
       }else {
           if (!empty($friend['beginid'])){
               
               $beginid  =  $friend['beginid'];
               $ischat   =  true;
           }else{
               //二人聊天专用id，这两个人的聊天记录，就按这个查询
               $beginid  =  $this->searchBeginid(array('toid'=>$data['toid'],'fromid'=>$data['fromid'],'tusertype'=>$data['tusertype'],'fusertype'=>$data['fusertype']));
               
               $this->upFriend(array('id'=>$friend['id']),array('beginid'=>$beginid));
               
               $ischat  =  true;
           }
       }
       
       $return  =  array(
           'beginid'  =>  $beginid,
           'ischat'   =>  $ischat
       );
       return $return;
   }
   /**
    * 处理初始biginid
    */
   private function searchBeginid($data = array())
   {
       $chatto    =  $this -> getChatLog(array('from'=>$data['fromid'],'fusertype'=>$data['fusertype'],'to'=>$data['toid'],'tusertype'=>$data['tusertype']));
       $chatfrom  =  $this -> getChatLog(array('from'=>$data['toid'],'fusertype'=>$data['tusertype'],'to'=>$data['fromid'],'tusertype'=>$data['fusertype']));
       
       if (!empty($chatto['beginid'])){
           
           $beginid  =  $chatto['beginid'];
           
       } elseif (!empty($chatfrom['beginid'])){
           
           $beginid  =  $chatfrom['beginid'];
           
       } else {
           
           $return['ischat']   =  false;
           $beginid  =  $data['fromid'].'-'.$data['toid'].'-'.$data['fusertype'].$data['tusertype'];
       }
       
       return $beginid;
   }
   /**
    * 信息发送时添加发送记录
    */
   function chatLog($data = array()){
       
       if (!empty($data['fromid']) && !empty($data['fusertype'])){
           
           if ($data['fromid'] == $data['nowid'] && $data['fusertype'] == $data['nowtype']){
               
               $br  =  $this->getBeginid($data);
               
               $beginid  =  $br['beginid'];
               // 查询对方是否将你加入黑名单
               $barr  =  array(
                   'fid'        =>  $data['fromid'],
                   'fusertype'  =>  $data['fusertype'],
                   'uid'        =>  $data['toid'],
                   'usertype'   =>  $data['tusertype'],
                   'state'      =>  2
               );
               $black  =  $this->getFriend($barr);
               if (!empty($black)){
                   $return['error']   =  3;
                   $return['errmsg']  =  '对方已将你拉入黑名单，无法'.$this->config['sy_chat_name'];
                   return $return;
               }
               
               $from     =  $this -> getMember(array('uid'=>$data['fromid'],'usertype'=>$data['fusertype']),array('field'=>'`uid`,`usertype`,`nickname`'));
               $to       =  $this -> getMember(array('uid'=>$data['toid'],'usertype'=>$data['tusertype']),array('field'=>'`uid`,`usertype`,`nickname`'));
               
               $this -> upChatLog(array('last'=>0), array('beginid'=>$beginid));
               
               $log['from']      =  $from['uid'];
               $log['to']        =  $to['uid'];
               $log['beginid']   =  $beginid;
               $log['fname']     =  $from['nickname'];
               $log['tname']     =  $to['nickname'];
               $log['fusertype'] =  $from['usertype'];
               $log['tusertype'] =  $to['usertype'];
               $log['content']   =  $data['content'];
               $log['sendTime']  =  $this->checkTime($data['timestamp']);
               $log['msgtype']   =  $data['msgtype'];
               $log['status']    =  2;
               $log['last']      =  1;
               $log['receive']   =  2;
               
               $nid  =  $this -> addChatLog($log);
                
               $return['error']   =  $nid ? 0 : -1;
               
           }else{
               require_once('cookie.model.php');
               $cookie  =  new cookie_model($this->db,$this->def);
               $cookie->unset_cookie();
               
               $return['error']   =  2;
               $return['errmsg']  =  '当前用户身份不符,请重新登录';
           }
       }else{
           $return['error']   =  1;
           $return['errmsg']  =  '请先登录';
       }
       
       return $return;
   }
   /**
    * 聊天记录分页
    * @param array $data
    */
   function getChatPage($data = array()){
       
       $toid  =  $data['toid'];
       
       $limit  = 20;
       $select_from = ($data['page'] - 1) * $limit;
       
       $br  =  $this->getBeginid($data);
       
       $chatList  =  $this -> getChatLogList(array('beginid'=>$br['beginid'],'orderby'=>'id','limit'=>array($select_from,$limit)));
       
       if (!empty($chatList)) {
           
           $chatjob   =  $this -> getChatLog(array('beginid'=>$br['beginid'],'msgtype'=>'job','orderby'=>'id,ASC'));
           
           $chatnum   =  $this -> getChatLogNum(array('beginid'=>$br['beginid']));
           
           $from      =  $this -> getMember(array('uid'=>$data['fromid'],'usertype'=>$data['fusertype']),array('field'=>'`nickname`,`avatar`'));
           
           $to        =  $this -> getMember(array('uid'=>$toid,'usertype'=>$data['tusertype']),array('field'=>'`nickname`,`avatar`'));
           
           $return['code']  =  0;
           
           foreach ($chatList as $k=>$v){
               
               $chatlog[$k]['content']   =  $v['content'];
               $chatlog[$k]['sendTime']  =  $v['sendTime'];
               $chatlog[$k]['fusertype'] =  $v['fusertype'];
               $chatlog[$k]['msgtype']   =  $v['msgtype'];
               $chatlog[$k]['timefromat']=  date('Y-m-d H:i',ceil($v['sendTime']/1000));
               
               if ($v['from'] == $data['fromid']){
                   
                   $chatlog[$k]['mine']      =  true;
                   $chatlog[$k]['username']  =  $from['nickname'];
                   $chatlog[$k]['avatar']    =  checkpic($from['avatar']);
                   
               }elseif ($v['to'] == $data['fromid']){
                   
                   $chatlog[$k]['mine']      =  false;
                   $chatlog[$k]['username']  =  $to['nickname'];
                   $chatlog[$k]['avatar']    =  checkpic($to['avatar']);
               }
               $chatlog[$k]['newjob']        =  0;
               if ($v['id'] == $chatjob['id']){
                   
                   if ($v['from'] == $data['fromid']){
                       
                       $chatlog[$k]['newjob']    =  1;
                   }else{
                       $chatlog[$k]['newjob']    =  2;
                   }
               }
           }
           $return['data']    =  $chatlog;
           $return['ismore']  =  ceil($chatnum/$limit) > $data['page'] ? true : false;
       }else{
           
           $return['code'] = -1;
       }
       return $return;
   }
   /**
    * 条件聊天时，判断个人是否有简历，并判断是否申请过该企业职位/已被企业邀请面试
    * @param array $data
    */
   function userToChat($data = array('nowtype'=>''))
   {
       if ($data['uid']){
           
           if(intval($data['uid']) == intval($data['comid'])){
               
               $return['code']  =  10;
           } elseif (!empty($data['nowtype']) && $data['nowtype'] != $data['usertype']) {
               
               $return['code'] = 11;
               
           } else {
               
               $this -> userinfo(array('uid'=>$data['uid'],'usertype'=>$data['usertype']));
               
               if ($this->config['sy_chat_type']==2){
                   
                   $data['tusertype']  =  2;
                   
                   $where['uid']       =  $data['uid'];
                   $where['defaults']  =  1;
                   
                   if ($data['jobtype'] == 'lt'){
                       
                       $data['tusertype']       =  3;
                       $where['height_status']  =  2;
                   }
                   $row  =  $this -> select_once('resume_expect', $where, '`r_status`,`state`');
                   
                   if(!empty($row)){
                       
                       $return['code']  =  1;
                       //简历通过审核
                       if ($row['state'] == 1){
                           
                           $useridmsg  =  $this -> select_once('userid_msg',array('uid'=>$data['uid'],'fid'=>$data['comid']),'id');
                           //已邀请面试
                           if (!empty($useridmsg)){
                               
                               $return['code']  =  5;
                               
                           }else{
                               $chat_num  =  $this->select_num('chat_log',array('from'=>$data['uid'],'to'=>$data['comid'],'fusertype'=>$data['usertype'],'tusertype'=>$data['tusertype']));
                               // 企业对个人有聊天记录，或者从招聘会来的，不再需要判断权限
                               if ($chat_num > 0 || intval($data['zid']) > 0){
                                   
                                   $return['code'] = 1;  //可以查看
                                   
                               }else{
                                   
                                   // 是否申请了职位
                                   if (!empty($data['jobid'])){
                                       
                                       $useridjob  =  $this -> select_once('userid_job',array('uid'=>$data['uid'],'job_id'=>$data['jobid']),'id');
                                       
                                   } else {
                                       
                                       $useridjob  =  $this -> select_once('userid_job',array('uid'=>$data['uid'],'com_id'=>$data['comid']),'id');
                                   }
                                   if (!$useridjob){
                                       
                                       $return['code'] = 9;
                                   }
                               }
                           }
                           
                       }elseif ($row['state'] == 3){
                           
                           $return['code']  =  6;
                           
                       }elseif ($row['state'] == 0){
                           
                           $return['code']  =  7;
                           
                       }elseif ($row['r_status'] == 2){
                           
                           $return['code']  =  8;
                       }
                   }else{
                       if ($data['jobtype'] == 'lt'){
                           
                           $return['code']  =  3;
                           
                       }else{
                           
                           $return['code']  =  2;
                       }
                   }
               }else {
                   
                   $return['code']  =  1;
               }
           }
       }else{
           
           $return['code']  =  4;
           
       }
       return $return;
   }
   /**
    * 条件聊天时，判断企业是否有查看个人简历的权限
    * @param array $data
    */
   function comToChat($data = array('nowtype'=>''))
   {
       if (!empty($data['fromid'])){
           
           if($data['fromid'] == $data['toid']){
               
               $return['code'] = 6;
               
           } elseif (!empty($data['nowtype']) && $data['nowtype'] != $data['fusertype']) {
               
               $return['code'] = 7;
               
           } else {
               
               if ($data['fusertype'] == 2){
                   
                   $company  =  $this->select_once('company',array('uid'=>$data['fromid']),'`r_status`');
                   
                   if ($company['r_status'] == 0){
                       $return['code'] = 8;
                   }elseif ($company['r_status'] == 2){
                       $return['code'] = 9;
                   }elseif ($company['r_status'] == 3){
                       $return['code'] = 10;
                   }
                   
               }elseif ($data['fusertype'] == 3){
                   
                   $lt  =  $this->select_once('lt_info',array('uid'=>$data['fromid']),'`r_status`');
                   
                   if ($lt['r_status'] == 0){
                       $return['code'] = 8;
                   }elseif ($lt['r_status'] == 2){
                       $return['code'] = 9;
                   }elseif ($lt['r_status'] == 3){
                       $return['code'] = 10;
                   }
               }
               if (empty($return['code'])){
                   
                   $this -> userinfo(array('uid'=>$data['fromid'],'usertype'=>$data['fusertype']));
                   
                   if ($this->config['sy_chat_type']==2){
                       
                       $chat_num  =  $this->select_num('chat_log',array('from'=>$data['fromid'],'to'=>$data['toid'],'fusertype'=>$data['fusertype'],'tusertype'=>$data['tusertype']));
                       // 企业对个人有聊天记录，或者从招聘会来的，不再需要判断权限
                       if ($chat_num > 0 || intval($data['zid']) > 0){
                           
                           $return['code'] = 0;  //可以查看
                           
                       }else{
                           $time  =  time();
                           
                           //先判断是否有正在招聘中的职位
                           if ($data['fusertype'] == 2){
                               
                               $return['code']  =  1;
                               $job   =  $this -> select_once('company_job',array('uid'=>$data['fromid'],'r_status'=>1,'status'=>0,'state'=>1),'`id`');
                               
                           }elseif ($data['fusertype'] == 3){
                               
                               $return['code']  =  2;
                               $job   =  $this -> select_once('lt_job',array('uid'=>$data['fromid'],'zp_status'=>0,'status'=>1,'r_status'=>array('<>',2)),'`id`');
                           }
                           //有正在招聘职位
                           if (!empty($job)){
                               
                               $right  =  $this -> select_once('chat_right',array('uid'=>$data['toid'],'comid'=>$data['fromid'],'usertype'=>$data['fusertype']));
                               
                               if (!empty($right)){
                                   $return['code'] = 0;  //可以查看
                               }else{
                                   //判断是否有聊天数量
                                   if ($data['fusertype'] == 2){
                                       
                                       $statis   =  $this -> select_once('company_statis',array('uid'=>$data['fromid']),'`vip_etime`,`rating_type`,`integral`,`chat_num`');
                                       
                                   }elseif ($data['fusertype'] == 3){
                                       
                                       $statis   =  $this -> select_once('lt_statis',array('uid'=>$data['fromid']),'`vip_etime`,`rating_type`,`integral`,`chat_num`');
                                   }
                                   
                                   $online    =  (int)$this->config['com_integral_online'];
                                   $chat_name = $this->config['sy_chat_name'];
                                   $spid      =  intval($data['spid']);
                                   /* 会员信息查询 */
                                   if($statis['vip_etime'] >= strtotime('today') || $statis['vip_etime'] == '0'){
                                       
                                       if($statis['rating_type'] == 1){  // 套餐模式
                                           
                                           /* 收费会员聊天已用完 */
                                           
                                           if($statis['chat_num'] == 0){ // 弹出购买提示
                                               
                                               if(!empty($spid)){
                                                   $res['code']  =  4;
                                                   $res['msg']	 =  '当前账户套餐余量不足，请联系主账户增配！';
                                                   
                                                   return $res;
                                               }else{
                                                   
                                                   if($online != 4){ // 非套餐消费模式
                                                       
                                                       if($online == 3){ // 积分消费
                                                           
                                                           $tmpJifen     =	  $this->config['integral_chat_num'] * $this->config['integral_proportion'];
                                                           
                                                           $res['msg']   =	  '你的等级特权已经用完，继续'.$chat_name.'将消费 '.$tmpJifen.$this->config['integral_pricename'].'，是否'.$chat_name.'？';
                                                           
                                                           /* 积分模式，是否需要充值判断 */
                                                           $res['jifen']     =   $tmpJifen;
                                                           $res['integral']  =   intval($statis['integral']);
                                                           $res['pro']       =   $this->config['integral_proportion'];
                                                       }else{
                                                           $tmpYuan      =   $this->config['integral_chat_num'];
                                                           
                                                           $res['msg']   =	  '你的等级特权已经用完，继续'.$chat_name.'将消费 '.$tmpYuan.' 元，是否'.$chat_name.'?';
                                                           $res['price'] =   $tmpYuan;
                                                       }
                                                       
                                                   }else{ // 套餐消费模式
                                                       
                                                       $res['msg']		  =	 "你的等级特权已经用完，你可以购买会员！";
                                                   }
                                                   
                                                   $res['code']    =  3;
                                                   $res['online']  =  $online;
                                                   $res['uid']     =  $data['toid'];
                                                   return $res;
                                               }
                                               
                                           }else{
                                               
                                               //收费会员套餐数量没用完的状态,直接扣除，开始聊天
                                               if ($data['fusertype'] == 2){
                                                   
                                                   $suid     =   $spid ? $spid : $data['fromid'];
                                                   $this -> update_once('company_statis',array('chat_num'=>array('-',1)),array('uid'=>$suid));
                                                   
                                               }elseif ($data['fusertype'] == 3){
                                                   
                                                   $this -> update_once('lt_statis',array('chat_num'=>array('-',1)),array('uid'=>$data['fromid']));
                                               }
                                               $this->insert_into('chat_right',array('uid'=>$data['toid'],'comid'=>$data['fromid'],'ctime'=>$time,'usertype'=>$data['fusertype']));
                                               
                                               $res['code']  =	0;
                                               
                                               return $res;
                                           }
                                           
                                       }else if($statis['rating_type'] == 2){    //时间会员
                                           
                                           $this->insert_into('chat_right',array('uid'=>$data['toid'],'comid'=>$data['fromid'],'ctime'=>$time,'usertype'=>$data['fusertype']));
                                           $res['code']  =	0;
                                           
                                           return $res;
                                       }
                                       
                                   }else{ // 过期会员
                                       
                                       if(empty($spid)){
                                           
                                           if($online != 4){    // 非套餐模式消费
                                               
                                               if($online == 3){
                                                   
                                                   $tmpJifen2			=	$this->config['integral_chat_num'] * $this->config['integral_proportion'];
                                                   $res['msg']			=	"你的会员已到期，请先购买会员！";
                                                   $res['jifen']		=   $tmpJifen2;
                                                   $res['integral']	    =   intval($statis['integral']);
                                                   $res['pro']			=   $this->config['integral_proportion'];
                                               }else{
                                                   
                                                   $tmpYuan2			=   $this->config['integral_chat_num'];
                                                   $res['msg']			=   "你的会员已到期，请先购买会员！";
                                                   $res['price']		=   $tmpYuan2;
                                               }
                                               
                                           }else{
                                               
                                               $res['msg']  =  "你的会员已到期，你可以购买会员！";
                                           }
                                           $res['online']   =  $online;
                                           $res['code']		=  3;
                                           $res['uid']      =  $data['toid'];
                                           
                                       }else {
                                           
                                           $res['code']  =  4;
                                           $res['msg']	 =  '当前账户会员已到期，请联系主账户升级！';
                                       }
                                       return $res;
                                   }
                               }
                           }
                       }
                   }else{
                       
                       $return['code']  =  0;
                   }
               }
           }
       }else{
           
           $return['code'] = 5;
       }
       return $return;
   }
   /**
    * 设置个人头像展示
    */
   private function setResumePhotoShow($data = array())
   {
       $resumePhoto  =	'';
       $sexArr		 =	 array(1, 152);
       
       if(empty($this -> config['user_pic']) || $this -> config['user_pic'] == 1){
           if($data['photo'] && $data['photo_status'] == 0 && $data['phototype'] != 1){
               $resumePhoto		=	$data['photo'];
           }else{
               if(in_array($data['sex'], $sexArr)){
                   $resumePhoto	=	$this -> config['sy_member_icon'];
               }else{
                   $resumePhoto	=	$this -> config['sy_member_iconv'];
               }
           }
       }elseif($this -> config['user_pic'] == 2){
           if($data['photo'] && $data['photo_status'] == 0){
               $resumePhoto		=	$data['photo'];
           }else{
               if(in_array($data['sex'], $sexArr)){
                   $resumePhoto	=	$this -> config['sy_member_icon'];
               }else{
                   $resumePhoto	=	$this -> config['sy_member_iconv'];
               }
           }
       }elseif($this -> config['user_pic'] == 3){
           if(in_array($data['sex'], $sexArr)){
               $resumePhoto		=	$this -> config['sy_member_icon'];
           }else{
               $resumePhoto		=	$this -> config['sy_member_iconv'];
           }
       }
       return $resumePhoto;
   }
   /**
    * 设置姓名展示
    */
   private function setUsernameShow($data = array())
   {
       $resUserName				=	'';
       
       if(empty($this -> config['user_name']) || $this -> config['user_name'] == 1){
           
           if($data['nametype'] == 1){
               $resUserName  =  $data['name'];
           }else if($data['nametype'] == 2){
               $resUserName  =  'NO.'. $data['eid'];
           }else{
               if($data['sex'] == 1){
                   $resUserName  =  mb_substr($data['name'], 0, 1, 'utf-8').'先生';
               }else{
                   $resUserName  =	mb_substr($data['name'], 0, 1, 'utf-8').'女士';
               }
           }
       }elseif($this -> config['user_name'] == 2){
           
           $resUserName  =  'NO.'. $data['eid'];
           
       }elseif($this -> config['user_name'] == 3){
           
           if($data['sex'] == 1){
               $resUserName  =  mb_substr($data['name'], 0, 1, 'utf-8').'先生';
           }else{
               $resUserName  =  mb_substr($data['name'], 0, 1, 'utf-8').'女士';
           }
       }elseif($this -> config['user_name'] == 4){
           $resUserName  =  $data['name'];
       }
       if(empty($resUserName)){
           $resUserName  =  $data['name'];
       }
       return $resUserName;
   }
   public function getPrepare($data)
   {
       
       $list  =  array();
       // 简历
       if ($data['usertype'] == 1){
           
           $logo     =  1;
           $expect   =  $this->select_once('resume_expect',array('uid'=>$data['uid'],'defaults'=>1,'state'=>'1'),'`id`,`uid`');
           
       }elseif ($data['usertype'] == 2 || $data['usertype'] == 3){
           
           $logo    =  2;
           $expect  =  $this->select_once('resume_expect',array('uid'=>$data['toid'],'defaults'=>1),'id,`uid`');
       }
       if (!empty($expect)){
           
           require_once ('resume.model.php');
           
           $resumeM  =  new resume_model($this->db, $this->def);
           
           $einfo    =  $resumeM -> getExpect(array('id'=>$expect['id']),array('needCache'=>1));
           
           $rinfo    =  $resumeM -> getResumeInfo(array('uid'=>$expect['uid']),array('field'=>'`name`,`sex`,`photo`,`birthday`','logo'=>$logo));
           
           $einfo['sex_n']   =  $rinfo['sex_n'];
           $einfo['age']     =  $rinfo['age'];
           $einfo['uname']   =  $rinfo['name'];
           $einfo['photo']   =  $rinfo['photo'];
           $einfo['weburl']  =  Url('resume',array('c'=>'show','id'=>$expect['id']));
           $einfo['wapurl']  =  Url('wap',array('c'=>'resume','a'=>'show','id'=>$expect['id']));
           
           $list['expect']  =  $einfo;
       }
       // 职位
       require_once ('job.model.php');
       
       $jobM  =  new job_model($this->db, $this->def);
       
       if ($data['usertype'] == 1){
           
           if ($data['totype'] == 2){
               // 招聘中职位
               $jobs  =  $jobM->getList(array('uid'=>$data['toid'],'state'=>1,'r_status'=>1,'status'=>0),array('chat'=>1));
               
               $company['wapurl']  =  Url('wap',array('c'=>'company','a'=>'show','id'=>$data['toid']));
               
               $list['company']    =  $company;
           }
       }elseif ($data['usertype'] == 2){
           // 招聘中职位
           $jobs  =  $jobM->getList(array('uid'=>$data['uid'],'state'=>1,'r_status'=>1,'status'=>0),array('chat'=>1));
           
       }
       
       if (!empty($jobs['list'])){
           
           foreach ($jobs['list'] as $k=>$v){
               
               $joblist[$v['id']] = $v;
               $joblist[$v['id']]['wapurl'] = Url('wap',array('c'=>'job','a'=>'comapply','id'=>$v['id']));
               $joblist[$v['id']]['weburl'] = Url('job',array('c'=>'comapply','id'=>$v['id']));
           }
           $list['joblist']  =  $joblist;
       }
       // 猎头职位
       if ($data['usertype'] == 3 || $data['totype'] == 3){
           
           if ($data['totype'] == 3){
               
               $uid  =  $data['toid'];
           }else{
               $uid  =  $data['uid'];
           }
           
           require_once ('lietoujob.model.php');
           
           $ltjobM  =  new lietoujob_model($this->db, $this->def);
           
           $jobs    =  $ltjobM->getList(array('uid'=>$uid,'status'=>1,'zp_status'=>0,'r_status'=>1));
           
           foreach ($jobs as $k=>$v){
               
               $joblist[$v['id']]['id']            =  $v['id'];
               $joblist[$v['id']]['name']          =  $v['job_name'];
               $joblist[$v['id']]['com_name']      =  $v['com_name'];
               $joblist[$v['id']]['job_salary']    =  $v['salary'];
               $joblist[$v['id']]['job_city_one']  =  $v['city_one_n'];
               $joblist[$v['id']]['job_city_two']  =  $v['city_two_n'];
               $joblist[$v['id']]['job_exp']       =  $v['exp_n'];
               $joblist[$v['id']]['job_edu']       =  $v['edu_n'];
           }
           $list['joblist']  =  $joblist;
           
           $company['wapurl']  =  Url('wap',array('c'=>'post','a'=>'headhunter','uid'=>$data['toid']));
           
           $list['company']    =  $company;
       }
       return $list;
   }
   function setMsg($data=array())
   {
       $return  =  array();
       if (!empty($data['toid']) && !empty($data['tusertype'])){
           
           if ($data['nowid'] == $data['toid'] && $data['nowtype'] == $data['tusertype']){
               
               $br  =  $this->getBeginid($data);
               
               if ($br['beginid']){
                   
                   $this -> upChatLog(array('status'=>1,'receive'=>1), array('beginid'=>$br['beginid']));
               }
           }else{
               require_once('cookie.model.php');
               $cookie  =  new cookie_model($this->db,$this->def);
               $cookie->unset_cookie();
               
               $return['error']   =  2;
               $return['errmsg']  =  '当前用户身份不符,请重新登录';
           }
       }else{
           $return['error']   =  1;
           $return['errmsg']  =  '请先登录';
       }
       return $return;
   }
   /**
    * 添加条件直聊下可直聊对象
    */
   public function addChatRight($data)
   {
       if (!empty($data)){
           
           $nid  =  $this -> insert_into('chat_right',$data);
       }
       
       return $nid;
   }
   /**
    * 条件直聊下查询聊天对象是否可直聊
    */
   function getChatRight($where = array(), $data = array())
   {
       $row  =  $this->select_once('chat_right',$where);
       
       return $row;
   }
   /**
    * 用户不在线，收到消息，提醒用户
    * @param array $data
    */
   
   function setUnSend($data = array())
   {
       //当前身份类型与接收消息身份类型一致时，才需要处理
       if ($data['fusertype'] == $data['nowtype']){
           
           $br  =  $this->getBeginid($data);
           
           if ($br['beginid']){
               
               $time        =  time();
               $today       =  strtotime('today');
               
               $unSend    =  $this->getChatLog(array('beginid'=>$br['beginid'],'remindTime'=>array('<>',''),'orderby'=>'`id`,DESC'),array('field'=>'`id`,`remindTime`'));
               
               $this -> upChatLog(array('remindTime'=>$time), array('beginid'=>$br['beginid'],'limit'=>1,'orderby'=>'`id`,DESC'));
               
               if (($unSend['remindTime'] && $unSend['remindTime']<$today) || empty($unSend['remindTime'])){
                   
                   // 短信提醒开启时，发送短信提醒，每天只1次
                   $msg  =  $this->select_once('moblie_msg',array('uid'=>$data['toid'],'content'=>array('like',$this->config['sy_chat_name']),'orderby'=>'id'),'`ctime`');
                   
                   if ($msg['ctime'] < $today){
                       $member   =  $this->select_once('member',array('uid'=>$data['toid']),'`uid`,`username`,`moblie`');
                       
                       if ($this->config['sy_msg_chat'] == 1){
                           
                           $msgData  =  array(
                               'uid'        =>  $member['uid'],
                               'username'   =>  $member['username'],
                               'mobile'     =>  $member['moblie'],
                               'date'       =>  date('Y-m-d/H:i:s'),
                               'chat_name'  =>  $this->config['sy_chat_name'],
                               'type'       =>  'chat'
                           );
                           
                           require_once ('notice.model.php');
                           
                           $noticeM   =  new notice_model($this->db, $this->def);
                           
                           $result = $noticeM -> sendSMSType($msgData);
                       }
                   }
               }
               // app推送和微信模板提醒，每4小时一次
               if (($unSend['remindTime'] && $unSend['remindTime']< ($time - 2400)) || empty($unSend['remindTime'])){
                   // app推送
                   include_once ('push.model.php');
                   $pushM = new push_model($this->db, $this->def);
                   
                   $pushM->pushMsg('chat',
                       array(
                           'fuid'      =>  $data['fromid'],
                           'puser'     =>  $data['toid'],
                           'tid'       =>  0,
                           'title'     =>  $this->config['sy_webname'],
                           'content'   =>  '您收到新的'.$this->config['sy_chat_name'].'信息，请注意查看！',
                       )
                       );
                   
                   $member   =  $this->select_once('member',array('uid'=>$data['toid']),'`wxid`,`wxopenid`');
                   
                   // 微信模板通知
                   if (!empty($member['wxid'])){
                       
                       $sendInfo  =  array('wxid'=>$member['wxid']);
                       
                   }elseif (!empty($member['wxopenid'])){
                       
                       $sendInfo  =  array('wxid'=>$member['wxopenid']);
                   }
                   if (!empty($sendInfo['wxid'])){
                       // 取得聊天双方uid
                       if ($data['tusertype'] == 1){
                           $userid  =  $data['toid'];
                           
                           if ($data['fusertype'] == 2){
                               
                               $comid  =  $data['fromid'];
                               
                           }elseif ($data['fusertype'] == 3){
                               
                               $ltid   =  $data['fromid'];
                           }
                           
                       }else{
                           $userid  =  $data['fromid'];
                           
                           if ($data['tusertype'] == 2){
                               
                               $comid  =  $data['toid'];
                               
                           }elseif ($data['tusertype'] == 3){
                               
                               $ltid   =  $data['toid'];
                           }
                       }
                       //取得聊天沟通意向
                       $jobChat  =  $this->getChatLog(array('beginid'=>$br['beginid'],'content'=>array('like','jobid'),'orderby'=>'`id`,DESC'),array('field'=>'`content`'));
                       
                       if (!empty($jobChat)){
                           
                           $jobid   =  trim(str_replace('jobid=', '',$jobChat['content']));
                           
                           if (isset($comid)){
                               
                               $job     =  $this->select_once('company_job',array('id'=>$jobid),'`name`');
                               $expect  =  mb_substr($job['name'], 0,20,'utf-8');
                               
                           }elseif (isset($ltid)){
                               
                               $job     =  $this->select_once('lt_job',array('id'=>$jobid),'`job_name`');
                               $expect  =  mb_substr($job['job_name'], 0,20,'utf-8');
                           }
                           
                       }else{
                           
                           $jl      =  $this->select_once('resume_expect',array('uid'=>$userid,'defaults'=>1),'`name`');
                           $expect  =  $jl['name'];
                       }
                       // 取得姓名
                       if (!empty($userid)){
                           
                           $qyid  =  isset($comid) ? $comid : $ltid;
                           // 聊天对象是个人，则发送方为企业/猎头
                           if ($data['tusertype'] == 1){
                               
                               $chat_member  =  $this->select_once('chat_member',array('uid'=>$qyid,'usertype'=>$data['fusertype']),'`linkman`');
                               $name         =  $chat_member['linkman'];
                               
                           }else{
                               
                               $resume  =  $this->select_once('resume',array('uid'=>$userid),'`name`,`sex`,`nametype`,`def_job`');
                               $down    =  $this->select_num('down_resume',array('uid'=>$userid,'comid'=>$qyid));
                               
                               if ($down > 0){
                                   
                                   $name   =  $resume['name'];
                               }else{
                                   
                                   $nameArr  =  array(
                                       'name'     => $resume['name'],
                                       'sex'      => $resume['sex'],
                                       'nametype' => $resume['nametype'],
                                       'eid'      => $resume['def_job']
                                   );
                                   $name   =  $this->setUsernameShow($nameArr);
                               }
                           }
                       }
                       
                       if (!empty($name) && !empty($expect)){
                           
                           include_once ('weixin.model.php');
                           $weixinM = new weixin_model($this->db, $this->def);
                           
                           $sendInfo['name']    =  $name;
                           $sendInfo['expect']  =  $expect;
                           $sendInfo['time']    =  date('Y-m-d H:i:s');
                           
                           $weixinM->sendWxChat($sendInfo);
                       }
                   }
               }
           }
       }
   }
   /**
    * 从聊天平台获取token
    */
   function getToken($uid = ''){
       
       $member  =  $this->select_once('chat_member',array('uid'=>$uid));
       // token未过期的不用重新获取
       if ((intval($member['expires_in']) + 600) < time()){
           
           $appkey   =  trim($this->config['sy_chat_appkey']);
           $appcret  =  trim($this->config['sy_chat_appsecret']);
           
           $url		 =  'https://yunliao.phpyun.com/gettoken.php';
           $url		.=  "?appkey=".$appkey."&appsecret=".$appcret."&suid=".$uid;
           
           if (extension_loaded('curl')){
               $file_contents 	= 		CurlGet($url);
               
           }else if(function_exists('file_get_contents')){
               
               $file_contents	= 		file_get_contents($url);
           }
           
           if (isset($file_contents)){
               
               $result  =  json_decode($file_contents,true);
               
               $this->update_once('chat_member',array('token'=>$result['token'],'expires_in'=>$result['expires_in']),array('uid'=>$uid));
               
               $return  =  array('token'=>$result['token']);
               
               return $return;
           }
       }else{
           
           $return  =  array('token'=>$member['token']);
           
           return $return;
       }
   }
   /**
    * 查询单条聊天用户关系
    */
   function getFriend($where = array())
   {
       if (!empty($where)){
           
           $row  =  $this->select_once('chat_friend',$where);
           
           return $row;
       }
   }
   /**
    * 查询单条聊天用户关系
    */
   function getFriendList($where = array(),$data = array('utype'=>''))
   {
       if (!empty($where)){
           
           $list  =  $this->select_all('chat_friend',$where);
           
           if ($data['utype'] == 'admin'){
               
               $uids = $cuids = array();
               
               foreach($list as $val){
                   $uids[]   =  $val['uid'];
                   $cuids[]  =  $val['fid'];
               }
               $all     =  array_merge($uids,$cuids);
               $alluid  =  array_unique($all);
               
               $member  =  $this->select_all('member',array('uid'=>array('in',pylode(',', $alluid))),'`uid`,`username`');
               
               if(!empty($member)){
                   
                   foreach($list as $k=>$v){
                       
                       foreach($member as $val){
                           
                           if($val['uid'] == $v['uid']){
                               
                               $username  =  $val['username'];
                               
                               if ($val['usertype'] == 1){
                                   
                                   $username .= '(个人)';
                                   
                               }elseif ($val['usertype'] == 2){
                                   
                                   $username .= '(企业)';
                               }
                               $list[$k]['username']  =  $username;
                           }
                           if($val['uid'] == $v['fid']){
                               
                               $list[$k]['rusername']  =  $val['username'];
                           }
                       }
                   }
               }
           }
           return $list;
       }
   }
   /**
    * 添加聊天用户关系
    */
   function addFriend($data = array())
   {
       if (!empty($data)){
           
           $nid  =  $this->insert_into('chat_friend',$data);
           
           return $nid;
       }
   }
   /**
    * 修改聊天用户关系
    */
   function upFriend($where = array(), $data = array())
   {
       if (!empty($where) && !empty($data)){
           
           $nid  =  $this->update_once('chat_friend',$data, $where);
           
           return $nid;
       }
   }
   /**
    * 检查时间戳，如与服务器时间差别太大，按服务器时间来
    */
   private function checkTime($time){
       
       $now  =  time();
       
       if ((round($time/1000)-300 > $now) || (round($time/1000)+300 < $now)){
           return $now.'000';
       }else{
           return $time;
       }
   }
}
?>